from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from unfold.admin import ModelAdmin
from unfold.forms import AdminPasswordChangeForm, UserChangeForm, UserCreationForm

from identify.models import User

# 取消注册内置的Group模型
try:
    admin.site.unregister(Group)
except admin.sites.NotRegistered:
    pass


@admin.register(User)
class UserAdmin(BaseUserAdmin, ModelAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm

    # 重写字段集，移除对groups和user_permissions的引用
    fieldsets = (
        (None, {"fields": ("email", "password")}),
        (_("Personal info"), {"fields": ("nickname", "avatar", "bio")}),
        (_("Permissions"), {"fields": ("is_active", "is_superuser")}),
        (_("Important dates"), {"fields": ("last_login", "date_joined")}),
    )

    add_fieldsets = (
        (
            None,
            {
                "classes": ("wide",),
                "fields": ("email", "nickname", "password1", "password2"),
            },
        ),
    )

    # 重写list_filter，移除对groups的引用
    list_filter = ("is_superuser", "is_active")

    # 移除对groups和user_permissions的filter_horizontal引用
    filter_horizontal = ()

    # 在列表页显示头像、用户名等信息
    list_display = ("avatar_preview", "email", "nickname", "is_active", "is_superuser")

    # 设置排序字段为email而不是username
    ordering = ("email",)

    # 头像预览功能
    @admin.display(description="头像预览")
    def avatar_preview(self, obj):
        if obj.avatar:
            return mark_safe(
                f'<img src="{obj.avatar.url}" style="width:32px; height:32px; border-radius:50%;">'
            )
        return "无头像"

    def has_add_permission(self, request):
        # 只有超级用户可以添加用户
        return request.user.is_superuser

    def has_delete_permission(self, request, obj=None):
        # 只有超级用户可以删除用户
        return request.user.is_superuser

    def has_change_permission(self, request, obj=None):
        # 只有超级用户可以修改用户
        return request.user.is_superuser

    def get_queryset(self, request):
        # 只有超级用户可以看到所有用户
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        # 普通用户无法看到任何用户（包括自己）
        return qs.none()

    def get_fieldsets(self, request, obj=None):
        # 只有超级用户可以访问，直接返回字段集
        if not obj:
            # 添加用户时使用add_fieldsets
            return self.add_fieldsets
        if request.user.is_superuser:
            return self.fieldsets
        # 非超级用户不能访问任何字段集
        return tuple()
